<template>
  <div id="projectTosComponent">

    <div name="开发信息提示" v-if="isInDevMode">
      selectedProjectTosViewList: {{ selectedProjectTosViewList[0] }}
      <hr/>
      clickedProjectTosView: {{ clickedProjectTosView }}
      <hr/>
      selectedProjectIds: {{ selectedProjectIds }}
      <hr/>
      clickedProjectId: {{ clickedProjectId }}
      <hr/>


    </div>


    <!--按钮组-->
    <el-row :inline="true" style="margin-bottom: 10px">

      <!--新增-->
      <el-button class="headerButton" type="primary" size="mini" plain
                 :disabled="selectedProjectIds.length != 1 "
                 @click="handleClickCreateCollectionButton">
        新增
      </el-button>
      <!--修改-->
      <el-button class="headerButton" type="primary" size="mini" plain
                 :disabled="selectedCollections.length !== 1 "
                 @click="handleClickEditCollectionButton">
        修改
      </el-button>

      <!--删除-->
      <el-button class="headerButton" type="danger" size="mini" plain
                 :disabled="selectedCollections.length === 0"
                 @click="handleClickDeleteCollectionButton">
        删除
      </el-button>

      <!--计费-->
      <el-button class="headerButton" type="danger" size="mini" plain
                 :disabled="selectedProjectIds.length === 0"
                 @click="handleClickAutoCalCollectionButton">
        计费
      </el-button>

      <!--对账-->
      <el-button class="headerButton" type="warning" size="mini" plain
                 :disabled="selectedCollections.length === 0"
                 @click="handleClickReconcliceCollectionButton">
        对账
      </el-button>

    </el-row>


    <div name="开发信息提示" v-if="isInDevMode">
      vBillCollectionList: {{ vBillCollectionList[0] }}
    </div>


    <!--收款List table-->
    <el-row class="table-container">
      <el-table row-key="billCollectionId"
                default-expand-all height="300"
                :data="vBillCollectionList"
                @selection-change="handleSelectionChange"
                v-loading="loading"
                :row-class-name="collectionRowClassNameByStatus"
                border>
        <el-table-column type="selection" align="center" width="42"/>

        <el-table-column prop="billCollectionId" label="ID" align="center" width="80"/>

        <el-table-column prop="collectionStatusCn" label="费项状态" align="center" width="80"/>

        <el-table-column prop="amount" label="金额" align="center" width="80"/>

        <el-table-column prop="currencyCn" label="币别" align="center" width="80"/>

        <el-table-column prop="statementNo" label="对账单号" align="center" width="150">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="handleClickStatementNo(scope.row)">
              {{ scope.row.statementNo }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="basicFeeName" label="费目" align="center" width="150"/>

        <el-table-column prop="feeServiceName" label="服务" align="center" width="80"/>

        <el-table-column prop="unitPrice" label="单价" align="center" width="100"/>

        <el-table-column prop="workNum" label="计费量" align="center" width="80"/>

        <el-table-column prop="workNumB" label="计费量2" align="center" width="80"/>

        <el-table-column prop="taxRate" label="税率" align="center" width="80"/>

<!--        <el-table-column prop="exchangeRate" label="汇率" align="center" width="50"/>-->

        <el-table-column prop="exchangeAmount" label="本币金额" align="center" width="80"/>

        <el-table-column prop="conCode" label="合同" align="center" width="200"/>

        <el-table-column prop="customerNam" label="委托客户" align="center" width="250"/>

        <el-table-column prop="remark" label="备注" align="center" width="250">
          <template slot-scope="scope">
            <div v-html="addLineBreaks(scope.row.remark)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="createNickName" label="创建人" align="center" width="100"/>

        <el-table-column prop="createTime" label="创建时间" align="center" width="160"/>

        <el-table-column prop="updateNickName" label="更新人" align="center" width="100"/>

        <el-table-column prop="updateTime" label="更新时间" align="center" width="160"/>

        <el-table-column prop="collectionSourceCn" label="生成方式" align="center" width="80"/>
      </el-table>
    </el-row>

    <!--统计数据-->
    <el-row class="table-container">
      <!--勾选共计：X条，金额：X元-->
      <span style="color: red; font-size: 20px;">勾选共计：{{
          selectedCollectionsCount
        }}条，金额：{{ selectedCollectionsTotalAmount }}元，计费量：{{
          selectedCollectionsTotalWorkNumByService
        }}，计费量2：{{ selectedCollectionsTotalWorkNumBByService }}</span>
    </el-row>


    <!-- 新增或者修改 Collection 弹窗-->
    <add-or-update-collection-dialog
      ref="addOrUpdateCollectionDialog"
      :run-mode="addOrUpdateCollectionDialogRunMode"
      :collection-id="selectedCollectionIds[0]?selectedCollectionIds[0]:''"
      :project-id="projectIdParam"
      @addOrUpdateSuccess="listVBillCollectionByProjectIds(listProjectIdParam)"
    />


    <!--打印帆软报表 dialog-->
    <print-fine-report-dialog
      :query-key-word="'对账单'"
      :string-after-url="`${billStatementId}`"
      :dialog-title="'打印对账单'"
      :style="{margin: '10px'}"
      ref="printFineReportDialog"
      @confirmStatement="handleConfirmStatement"
    ></print-fine-report-dialog>


  </div>
</template>

<script>
import {listVBillCollectionByProjectIds} from "@/api/finance/vBillCollection/vBillCollection";
import {deleteBillCollection, autoCollection,autoCollectionall} from "@/api/finance/billCollection/billCollection";
import AddOrUpdateCollectionDialog
  from "@/views/business/components/collectionListComponent/component/AddOrUpdateCollectionDialog.vue";
import {generateBillStatement, confirmBillStatement} from "@/api/statement/billStatement";
import PrintFineReportDialog from "@/views/components/common/PrintFineReportDialog.vue";
import {oneKeyBindContract} from "@/api/business/vProjectTos";

export default {
  name: 'CollectionListComponent',
  components: {PrintFineReportDialog, AddOrUpdateCollectionDialog},
  props: {

    // 来自projectTos组件 被点击的项目
    clickedProjectTosView: {
      type: Object,
      default: () => {
        return {}
      }
    },

    // 来自projectTos组件 被勾选的项目
    selectedProjectTosViewList: {
      type: Array,
      default: () => {
        return []
      }
    },


  },
  data() {
    return {
      // 作弊码：从localStorage中获取是否处于开发模式，值为true或false
      isInDevMode: localStorage.getItem('isInDevMode') === 'true',


      // 收款List loading
      loading: false,
      // 收款列表
      vBillCollectionList: [],
      // 勾选的收款List
      selectedCollections: [],
      //对账单id
      billStatementId: '',

      status:1,
      // 新增或者修改 Collection 弹窗组件：运行模式
      addOrUpdateCollectionDialogRunMode: 'add',
    }
  },
  computed: {

    // clickedProjectId 被点击的项目id，转化为字符串
    clickedProjectId() {
      return `${this.clickedProjectTosView.projectId || ''}`;
    },


    // selectedProjectIds 被勾选的项目ids（转化为String，过滤null）
    selectedProjectIds() {
      return this.selectedProjectTosViewList.map(item => `${item.projectId || ''}`).filter(item => item);
    },
    
    projectIdParam() {
      if (!(this.clickedProjectId==='')) {
        return this.clickedProjectId
      }else{
        return this.selectedProjectIds[0]?this.selectedProjectIds[0]:''
      }
    },
    
    listProjectIdParam() {
      if (this.selectedProjectIds.length!==0){
        return this.selectedProjectIds
      }else if (!(this.clickedProjectId==='')) {
          return [this.clickedProjectId]
      }else{
        return []
      }
    },

    // 勾选的项目中，是否存在项目未绑定合同
    isExistProjectNotBindContractInSelectedProjectTosViewList() {
      // 遍历勾选的项目，如果存在项目未绑定合同，返回false
      for (let i = 0; i < this.selectedProjectTosViewList.length; i++) {
        if (!this.selectedProjectTosViewList[i].conId) {
          return true;
        }
      }
      return false;
    },

    // 勾选的收款费项，是否可以生成对账单
    isSelectCollectionCanGenerateBillStatement(row) {
      // 遍历勾选的收款费项，如果存在收款费项的委托用户不一样，返回false
      for (let i = 0; i < this.selectedCollections.length; i++) {
        if (this.selectedCollections[i].customerCod !== this.selectedCollections[0].customerCod) {
          return false;
        }
      }
      return true;
    },


    // selectedCollectionIds 勾选收款ids
    selectedCollectionIds() {
      return this.selectedCollections.map(item => item.billCollectionId);
    },
    // selectedCollectionsCount 勾选收款数量
    selectedCollectionsCount() {
      return this.selectedCollections.length;
    },
    // selectedCollectionsTotalAmount 勾选收款总金额
    selectedCollectionsTotalAmount() {
      let totalAmount = this.selectedCollections.reduce((total, item) => {
        return total + item.amount;
      }, 0);
      if (Math.floor(totalAmount)!==totalAmount){
        totalAmount = totalAmount.toFixed(2);
      }
      return totalAmount;
    },
    // selectedCollectionsTotalWorkNum 勾选收款总计费量
    selectedCollectionsTotalWorkNum() {
      return this.selectedCollections.reduce((total, item) => {
        return total + item.workNum;
      }, 0);
    },

    //selectedCollectionsTotalWorkNumByService 计费量 先把勾选的根据服务分组，再把服务分组的计费量相加，并用字符串拼接，如服务1：1，服务2：2
    selectedCollectionsTotalWorkNumByService() {
      // 创建一个空的Map变量serviceMap，用于存储服务和对应的计费量
      let serviceMap = new Map();

      // 对选中的集合进行遍历
      this.selectedCollections.forEach(item => {
        // 如果serviceMap中已经存在该服务，则将其计费量累加
        if (serviceMap.has(item.feeServiceName)) {
          serviceMap.set(item.feeServiceName, serviceMap.get(item.feeServiceName) + item.workNum);
        } else {
          // 如果serviceMap中不存在该服务，则将其添加到serviceMap中，并设置初始计费量
          serviceMap.set(item.feeServiceName, item.workNum);
        }
      });

      // 打印serviceMap，用于调试查看结果
      console.log(serviceMap);

      // 创建一个空字符串变量str，用于拼接服务和对应计费量的字符串
      let str = '';

      // 遍历serviceMap中的每一对键值对，将其拼接为指定格式的字符串
      serviceMap.forEach((value, key) => {
        if (Math.floor(value)!==value){
          value = value.toFixed(2);
        }
        str += `【${key}】：${value}，`;
      });

      // 返回拼接的字符串，去掉末尾的逗号
      return str.substring(0, str.length - 1);
    },

    selectedCollectionsTotalWorkNumBByService() {
      let serviceMap = new Map();
      this.selectedCollections.forEach(item => {
        if (serviceMap.has(item.feeServiceName)) {
          serviceMap.set(item.feeServiceName, serviceMap.get(item.feeServiceName) + item.workNumB);
        } else {
          serviceMap.set(item.feeServiceName, item.workNumB);
        }
      });
      console.log(serviceMap);
      let str = '';
      serviceMap.forEach((value, key) => {
        if (Math.floor(value)!==value){
          value = value.toFixed(2);
        }
        str += `【${key}】：${value}，`;
      });
      return str.substring(0, str.length - 1);
    }

  },
  watch: {

    // 如果 clickedProjectId 变化，重新获取收款列表
    clickedProjectId: {
      handler(newVal, oldVal) {
        if (!newVal) {
          // 如果 clickedProjectId 为空，清空收款列表
          this.vBillCollectionList = [];
          return;
        } else {
          this.listVBillCollectionByProjectIds([newVal]);
        }
      },
      immediate: true,
    },

    // 如果 selectedProjectIds 变化，重新获取收款列表
    selectedProjectIds: {
      handler(newVal, oldVal) {
        if (!Array.isArray(newVal) || newVal.length === 0 || newVal.every(item => item === null)) {
          // 如果 selectedProjectIds 为空，清空收款列表
          this.vBillCollectionList = [];
          return;
        } else {
          this.listVBillCollectionByProjectIds(newVal);
        }
      },
      immediate: true,
    },


  },
  methods: {
    addLineBreaks(str) {
      if(str!=null){
        return str.replace(/\n/g, '<br>');
      }
    },
    // 收款列表行样式
    collectionRowClassNameByStatus({row, rowIndex}) {
      if (row.statementStatus == 1) {
        //  确认对账
        return 'info-row-billCollection';
      } else if (row.statementStatus == 2) {
        //  确认收款
        return 'success-row-billCollection';
      } else if (row.statementStatus == 0) {
        //  生成对账单
        return 'warning-row-billCollection';
      }
      return '';
    },

    // 点击新增收款按钮
    handleClickCreateCollectionButton() {
      // 运行模式设置为'add'
      this.addOrUpdateCollectionDialogRunMode = 'add';

      // 打开弹窗
      this.$refs.addOrUpdateCollectionDialog.openDialog();

    },
    // 点击删除收款按钮
    handleClickDeleteCollectionButton() {
      // 弹窗确认
      this.$confirm('此操作将永久删除该收款, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除收款
        const res = await deleteBillCollection(this.selectedCollectionIds);
        if (res.code === 200) {
          // 提示删除成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 重新获取收款列表
          await this.listVBillCollectionByProjectIds(this.selectedProjectIds);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 点击修改收款按钮
    async handleClickEditCollectionButton() {

      // 设置addOrUpdateCollectionDialog的运行模式为'update'
      // this.addOrUpdateCollectionDialogRunMode = 'update';
      await this.setAddOrUpdateCollectionDialogRunMode('update');

      // 传递选中的收款ID
      // 已经通过props传递了selectedCollections，所以这里不需要再传递了

      // 打开弹窗
      this.$refs.addOrUpdateCollectionDialog.openDialog();


    },


    setAddOrUpdateCollectionDialogRunMode(model) {
      // 设置addOrUpdateCollectionDialog的运行模式为'update'
      this.addOrUpdateCollectionDialogRunMode = model;
    },


    // 点击自动计算收款按钮
    async handleClickAutoCalCollectionButton() {
      // 勾选项目中，存在项目未绑定合同
      if (this.isExistProjectNotBindContractInSelectedProjectTosViewList) {
        this.$message({
          type: 'warning',
          message: '存在未绑定合同的项目，请先绑定合同!'
        });
        return;
      }

      // 都已绑定合同，则对项目（selectedProjectIds）依次计费（autoCollection）
      const {selectedProjectIds} = this;
      
      console.log(selectedProjectIds)

      //判断计费类型是否唯一
    let arr=[];
      for (let i in this.selectedProjectTosViewList){
        console.log(this.selectedProjectTosViewList[i].projectType)
        arr[i]=this.selectedProjectTosViewList[i].projectType
      }
      arr = [...new Set(arr)];//利用SET去重
      console.log(arr)
      arr.length=='1' ? console.log('true') : console.log('false')
      
      if (arr.length=='1'){
        try {
          // 打开遮罩层
          this.$modal.loading("正在计费，请稍后...");
          // 发送请求，一键绑定合同
          const response = await autoCollectionall(selectedProjectIds)
          //   .catch(error =>{
          //   this.$message.error(error.toString());
          //   // 关闭遮罩层
          //   this.$modal.closeLoading();
          //   // 刷新列表
          //   this.listVBillCollectionByProjectIds(selectedProjectIds);
          // });

          // 根据响应结果，提示用户
          if (response.code === 200) {
            // 一键绑定合同成功
            this.$message.success(response.msg);
          } else {
            // 一键绑定合同失败
            this.$message.error(response.msg);
          }
          this.$modal.closeLoading();
          // 刷新列表
          await this.listVBillCollectionByProjectIds(selectedProjectIds);


          // const results = await Promise.all(selectedProjectIds.map(projectId => autoCollection(projectId)));
          //
          // for (const res of results) {
          //   // 如果有一个计费失败，则提示失败
          //   if (res.code !== 200) {
          //     this.$modal.msgError(res.msg);
          //   }
          // }
          //
          // // 全都成功，提示计费成功
          // this.$modal.msgSuccess('计费成功!');
          // // 重新获取收款列表
          // await this.listVBillCollectionByProjectIds(selectedProjectIds);
        } catch (error) {
          // 处理错误情况
          this.$message.error(error.toString());
          // 关闭遮罩层
          this.$modal.closeLoading();
          // 刷新列表
          await this.listVBillCollectionByProjectIds(selectedProjectIds);
        } finally {

        }
      }else {
        this.$message('请选择同一计费类型数据')
      }
    },


    //点击生成结算按钮
    handleClickReconcliceCollectionButton() {
      // 如果没有勾选收款 提示勾选收款
      if (this.selectedCollectionIds.length === 0) {
        this.$message({
          type: 'warning',
          message: '请勾选收款费项!'
        });
        return;
      }
      //遍历勾选的收款列表，判断是否有收款状态为已生成对账单的，如果有提示不能重复生成对账单
      for (let i = 0; i < this.selectedCollections.length; i++) {
        if (this.selectedCollections[i].collectionStatus == 1) {
          this.$message({
            type: 'warning',
            message: '不能重复生成对账单!'
          });
          return;
        }
      }
      if (this.isSelectCollectionCanGenerateBillStatement) {
        // 确认是否生成对账单
        this.$confirm('此操作将生成对账单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.$modal.loading("正在生成对账单，请稍后...");
          // 生成对账单
          const res = await generateBillStatement(this.selectedCollectionIds);
          if (res.code == 200) {
            // 提示生成对账单成功
            this.$message({
              type: 'success',
              message: '生成对账单成功!'
            });
            this.billStatementId = res.data.billStatementId
            // 重新获取收款列表
            await this.listVBillCollectionByProjectIds(this.selectedProjectIds);
            this.$modal.closeLoading();
            //打开帆软报表组件的弹窗
            this.$refs.printFineReportDialog.openDialog();
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消生成对账单'
          });
          this.$modal.closeLoading();
        });
      } else {
        //错误信息 所勾选的费项委托方不一致
        this.$message({
          type: 'warning',
          message: '所勾选的费项委托方不一致!'
        });
      }
    },

    // 收款勾选改变
    handleSelectionChange(selection) {
      this.selectedCollections = selection;
    },

    // list 收款 by 勾选的projectIds
    async listVBillCollectionByProjectIds(projectIds) {
      // 如果 projectIds 为空，不查询
      if (!projectIds || projectIds.every(item => item === null || item === undefined || item === '' || item === 'null') || projectIds.length === 0) {
        return;
      }
      // 去除 projectIds 中的 "null"
      projectIds = projectIds.filter(item => item !== null && item !== undefined && item !== '' && item !== 'null');
      // 查询收款列表
      this.loading = true;
      const res = await listVBillCollectionByProjectIds(projectIds);
      this.loading = false;
      if (res.code === 200) {
        // 赋值收款列表
        this.vBillCollectionList = res.data || [];
      } else {
        // 提示错误
        this.$message.error(res.message);
      }
    },

    //点击对账单号，打开打印对账单弹窗
    handleClickStatementNo(row) {
      //给billStatementId赋值，通过props传递到打印对账单弹窗
      this.billStatementId = row.statementId;
      this.$refs.printFineReportDialog.$props.stringAfterUrl = `${this.billStatementId}`
      //打开帆软报表组件的弹窗
      this.$refs.printFineReportDialog.openDialog();
    },

    // 确认对账
    handleConfirmStatement() {
      confirmBillStatement(this.billStatementId).then(res => {
        if (res.code == 200) {
          // 提示确认对账成功
          this.$message({
            type: 'success',
            message: '确认对账成功!'
          });
          // 重新获取收款列表
          this.listVBillCollectionByProjectIds(this.selectedProjectIds);
        }
      })
    }

  }
}
</script>

<style scoped>


.headerButton {
  margin-right: 10px;
}
</style>
<style>

.el-table .warning-row-billCollection {
  background: rgb(242, 243, 201);
}

.el-table .success-row-billCollection {
  background: rgb(144, 218, 236);
}

.el-table .info-row-billCollection {
  background: rgb(196, 235, 175);
}
</style>

